import { Injectable } from '@angular/core';
import { Platform } from 'ionic-angular';
import { Md5 } from "ts-md5/dist/md5";
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
/*
  Generated class for the JmessageProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
declare let JMessage: any;
@Injectable()
export class JmessageProvider {

  private JIM: any;//全局变量
  private chatList: any;//聊天内容保存

  public JPUSH_APPKEY = "5a7a0facc4d3fd9e43e63d7f";
  public JPUSH_SECRET = "172fdb62eb146a12c46f88c0";

  constructor(
    public platform: Platform,
    public http: HttpProvider,
    public storage: StorageProvider,
    public dialog: DialogProvider) {
    console.log('Hello JmessageProvider Provider');
    if (this.JIM == undefined) this.JIM = new JMessage();
  }

  // 生成签名的随机串
  private jpush_noncestr() {
    return Md5.hashStr(Math.random().toString(36).substr(2, 15));
  };
  // 生成签名的随机串
  private jpush_signature(appkey: any, timestamp: any, random_str: any, key: any) {
    let strParams = "appkey=" + appkey + "&timestamp=" + timestamp + "&random_str=" + random_str + "&key=" + key;
    return Md5.hashStr(strParams);
  };
  // 生成签名的时间戳
  private jpush_timestamp() {
    let timestamp = new Date().getTime();
    return parseInt(timestamp.toString()).toString();
  };
  //自动登陆
  public initLoadLogin() {
    let that = this;
    //判断用户是否已经登陆
    that.storage.getStorage('user').then((val) => {
      if (val != undefined) {
        //http请求登陆
        that.http.postJson('user', 'info', { id: val['uid'] }, true).then(res => {
          if (res['status'] == "200") {
            that.initLogin(res['data']['username'], res['data']['password']);
          } else {
            that.dialog.showToast("top", "您的IM用户登陆失败");
          }
        });
      }
    });
  }
  //初始化
  public initJmessage(callback: any) {
    let that = this;
    let noncestr = this.jpush_noncestr();
    let timestamp = this.jpush_timestamp();
    let signature = this.jpush_signature(this.JPUSH_APPKEY, timestamp, noncestr, this.JPUSH_SECRET);
    this.JIM.init({
      "appkey": this.JPUSH_APPKEY,
      "random_str": noncestr,
      "signature": signature,
      "timestamp": timestamp,
      "flag": true
    }).onSuccess(function (data) {
      //data.code 返回码
      //data.message 描述
      console.log(data);
      if (callback)
        callback();
    }).onFail(function (data) {
      // 同上
      console.log(data);
    });
  }
  //断线监听
  public initDisconnect() {
    let that = this;
    this.JIM.onDisconnect(function () {
      that.dialog.showToast("top", "您的IM已经断开连接");
      //自动连接
    });
  }
  //注册用户
  public initRegist(username: any, password: any, callback: any) {
    this.JIM.register({
      'username': username,
      'password': password
    }).onSuccess(function (data) {
      //data.code 返回码
      //data.message 描述
      console.log(data);
      if (callback)
        callback();
    }).onFail(function (data) {
      // 同上
      console.log(data);
      if (callback)
        callback();
    });
  }
  //登陆用户
  public initLogin(username: any, password: any) {
    //如果登陆，先注销，再登陆
    this.JIM.login({
      'username': username,
      'password': password
    }).onSuccess(function (data) {
      //data.code 返回码
      //data.message 描述
      console.log(data);
    }).onFail(function (data) {
      // 同上
      console.log(data);
    });
  }
  //发送单聊文本
  public sendSingleMsg(target_username: any, content: any, callback: any) {
    // 发送消息
    this.JIM.sendSingleMsg({
      'target_username': target_username,
      'content': content
    }).onSuccess(function (data) {
      //data.code 返回码
      //data.message 描述
      //data.msg_id 发送成功后的消息 id
      //data.ctime_ms 消息生成时间,毫秒
      //data.appkey 用户所属 appkey
      //data.target_username 用户名
      //msg.content 发送成功消息体,见下面消息体详情
      console.log(data);
      if (callback)
        callback();
    }).onFail(function (data) {
      //data.code 返回码
      //data.message 描述
      console.log(data);
    });
  }
  //发送单聊图片
  public sendSinglePic(target_username: any, base64: any, callback: any) {
    // 发送消息
    this.JIM.sendSinglePic({
      'target_username': target_username,
      'image': base64
    }).onSuccess(function (data) {
      //data.code 返回码
      //data.message 描述
      //data.msg_id 发送成功后的消息 id
      //data.ctime_ms 消息生成时间,毫秒
      //data.appkey 用户所属 appkey
      //data.target_username 用户名
      //msg.content 发送成功消息体,见下面消息体详情
      console.log(data);
      if (callback)
        callback();
    }).onFail(function (data) {
      //data.code 返回码
      //data.message 描述
      console.log(data);
    });
  }
  //获取会话列表
  public initConversation() {
    let promise = new Promise((success, fail) => {
      this.JIM.getConversation().onSuccess(function (data) {
        //data.code 返回码
        //data.message 描述
        //data.conversations[] 会话列表，属性如下示例
        //data.conversations[0].extras 附加字段
        //data.conversations[0].unread_msg_count 消息未读数
        //data.conversations[0].name  会话名称
        //data.conversations[0].appkey  appkey(单聊)
        //data.conversations[0].username  用户名(单聊)
        //data.conversations[0].nickname  用户昵称(单聊)
        //data.conversations[0].avatar  头像 media_id 
        //data.conversations[0].mtime 会话最后的消息时间戳
        //data.conversations[0].gid 群 id(群聊)
        //data.conversations[0].type  会话类型(3 代表单聊会话类型，4 代表群聊会话类型)
        console.log(data);
        if (success)
          success();
      }).onFail(function (data) {
        //data.code 返回码
        //data.message 描述
        console.log(data);
        if (fail)
          fail();
      });
    });
    //异步回调
    return promise;
  }
  //实时接收信息
  public initMsgReceive(callback: any) {
    this.JIM.onMsgReceive(function (data) {
      // data.messages[]
      // data.messages[].ctime_ms
      // data.messages[].msg_type 会话类型
      // data.messages[].msg_id
      // data.messages[].from_appey 单聊有效
      // data.messages[].from_username 单聊有效
      // data.messages[].from_gid 群聊有效
      // data.messages[].need_receipt
      // data.messages[].content
      // data.messages[].custom_notification.enabled
      // data.messages[].custom_notification.title
      // data.messages[].custom_notification.alert
      // data.messages[].custom_notification.at_prefix
      console.log(data);
      if (callback)
        callback(data);
    });
  }
  //离线消息接收信息
  public initSyncConversation(callback: any) {
    this.JIM.onSyncConversation(function (data) {
      // data[]
      // data[].msg_type 会话类型
      // data[].from_appey 单聊有效
      // data[].from_username 单聊有效
      // data[].from_gid 群聊有效
      // data[].unread_msg_count 消息未读数
      // 消息已读回执状态，针对自己发的消息
      // data[].receipt_msgs[]
      // data[].receipt_msgs[].msg_id
      // data[].receipt_msgs[].unread_count
      // data[].receipt_msgs[].mtime
      // 消息列表
      // data[].msgs[]
      // data[].msgs[].msg_id
      // data[].msgs[].content
      // data[].msgs[].msg_type
      // data[].msgs[].ctime_ms
      // data[].msgs[].need_receipt
      // data[].msgs[].custom_notification.enabled
      // data[].msgs[].custom_notification.title
      // data[].msgs[].custom_notification.alert
      // data[].msgs[].custom_notification.at_prefix
      console.log(data);
      if (callback)
        callback(data);
    });
  }

  //获取资源路径
  public getResource(media_id: any, callback: any) {
    this.JIM.getResource({
      'media_id': media_id,
    }).onSuccess(function (data) {
      //data.code 返回码
      //data.message 描述
      //data.url 资源临时访问路径
      console.log(data);
      if (callback)
        callback(data);
    }).onFail(function (data) {
      //data.code 返回码
      //data.message 描述
      console.log(data);
    });
  }
}
